const express = require('express');
const router = express.Router();
const userModel = require('../db/models/userModel');
const md5 = require('md5');
const STATUSCODE = require('../utils/constants');
const {signToken} = require('../utils/tokenUtils');
const verifyTokenM = require('../middlewares/verifyToken');

// 登录接口
router.post('/admin/login', async (req, res) => {
    let { username, pwd } = req.body;
    // 从数据库中查找与data数据相匹配的数据// 如果找到就是登录成功// 否则就是登录失败

    try {
        let user = await userModel.findOne({ username, pwd: md5(pwd) });
        if (user) {// 登录成功
            res.json({
                code: STATUSCODE.SUCCESS,
                message: "登录成功",
                data: {
                    token:signToken({username,user_id:user._id}),
                    user
                }
            })
        } else {// 登录失败
            res.json({
                code: STATUSCODE.DATAERROR,
                message: "登录失败"
            })
        }
    }catch(err){
        console.log(err);
        res.json({
            code:STATUSCODE.SERVERERROR,
            message:"服务器错误"
        })
    }
})

// 获取登录用户信息
router.get('/admin/info',verifyTokenM,async (req,res)=>{
    let user_id = req.userInfo.user_id;
    try{
        let data = await userModel.findById(user_id);
        res.json({
            code:STATUSCODE.SUCCESS,
            message:"获取登录用户信息成功",
            data
        })
    }catch(err){
        res.json({
            code:STATUSCODE.SERVERERROR,
            message:"服务器错误"
        })
    }
})

module.exports = router;